const http = require("http");
const url = require("url");
const querystring = require("querystring");
const util = require("util");
const user = require("./user_file");

var server=http.createServer(function (request, response) {
    var pathname=url.parse(request.url).pathname;
    var query=pathname.split("/");
    var callback=function(error,result){
        if(error){
            response.writeHead(200, {'Content-Type': 'text/plain'});
            response.write(error.message);
            response.end();
            console.log(error.message);
        }
        else{
            response.writeHead(200, {'Content-Type': 'application/json'});
            response.write(JSON.stringify(result));
            response.end();
        }
    }

    if(request.method==="GET"){
        if(query.length>=3){
            var id = query[2];
            user.find(id,callback);
        }
        else{
            user.listAll(callback);
        }
        return 0;
    }
    
    var post = '';
    request.on('data', function(chunk){
        post += chunk;
    });
    request.on('end', function(){
        post = querystring.parse(post);
        if(request.method==="POST"){
            user.insert(post,callback);
        }
        else if(request.method==="PUT"){
            user.update(post,callback);
        }
        else if(request.method==="DELETE"){
            user.delete(post,callback);
        }
    });
});
server.listen(8888);

console.log('Server running at http://127.0.0.1:8888/');